﻿using Newtonsoft.Json;
using suirui.ZhuMu.Common;
using suirui.ZhuMu.Log;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace suirui.ZhuMu.Common
{
    public static class APIResponseHelper
    {
        #region API统一调度函数
        public static async Task<string> APIResponseForm(string _APIUrl, StringBuilder data)
        {
            string contentType = "application/x-www-form-urlencoded;charset=UTF-8";
            return await APIResponse(_APIUrl, data.ToString(),"", contentType);
        }
        #endregion

        #region API统一调度函数
        public static async Task<string> APIResponse(string url, string data, string token = null, string contentType = "application/json; charset=utf-8", string MethodType = "POST")
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(url))
            {
                try
                {
                    Uri address = new Uri(url);
                    // Create the web request   
                    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
                    // Set type to POST   k
                    request.Method = MethodType;
                    request.ContentType = contentType;
                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        request.Headers.Add("Authorization", token.StartsWith("Bearer ") ? token : "Bearer " + token);
                    }
                    // Create a byte array of the data we want to send   
                    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
                    // Set the content length in the request headers   
                    request.ContentLength = byteData.Length;
                    // Write data   
                    using (Stream postStream = request.GetRequestStream())
                    {
                        postStream.Write(byteData, 0, byteData.Length);
                    }
                    // Get response   
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        // Get the response stream   
                        StreamReader reader = new StreamReader(response.GetResponseStream(), UTF8Encoding.UTF8);
                        result = reader.ReadToEnd().ToString();
                    }
                }
                catch (Exception ex)
                {
                    DefaultLogFactory.Instance.Zhumu_Loger.Error(new { Url = url, PostData = data, Result = result, ExceptionMsg = ex.Message });
                    result = ex.Message;
                }
                finally
                {
                    if (url.Contains("zhumu.me") ||
                        (url.Contains("125339.com")))
                    {
                        DefaultLogFactory.Instance.Zhumu_Loger.Info(new { Url = url, PostData = data, Result = result });
                    }
                }
            }
            return result;
        }

        public static string APIResponseByDic(string url, string data, Dictionary<string, string> headers = null)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(url))
            {
                try
                {
                    Uri address = new Uri(url);
                    // Create the web request   
                    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
                    if (headers != null)
                    {
                        foreach (var item in headers)
                        {
                            request.Headers.Set(item.Key, item.Value);
                        }
                    }
                    // Set type to POST   k
                    request.Method = "POST";
                    request.ContentType = "application/json";
                    // Create a byte array of the data we want to send   
                    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
                    // Set the content length in the request headers   
                    request.ContentLength = byteData.Length;
                    // Write data   
                    using (Stream postStream = request.GetRequestStream())
                    {
                        postStream.Write(byteData, 0, byteData.Length);
                    }
                    // Get response   
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        // Get the response stream   
                        StreamReader reader = new StreamReader(response.GetResponseStream(), UTF8Encoding.UTF8);
                        result = reader.ReadToEnd().ToString();
                    }
                    DefaultLogFactory.Instance.Exception_Loger.Error("调用结果" + result);
                }
                catch (Exception ex)
                {
                    result = ex.Message;
                    DefaultLogFactory.Instance.Exception_Loger.Error("调用接口异常ex=" + ex.Message);
                }
                finally
                {
                    //LogHelper.DefaultLoger.Info(new { Url = url, PostData = data, Result = result });
                }

            }
            return result;
        }
        #endregion


        public static async Task<string> HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "application/json; charset=utf-8"; 
 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
 
            return retString;
        }

    /// <summary>
    /// json转为匿名对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="json"></param>
    /// <param name="anonymousTypeObject"></param>
    /// <returns></returns>
    public static T DesAnonymousType<T>(string json, T anonymousTypeObject)
        {
            return JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
        }
    }

    
}

